package com.wuseguang.springcloud.mina;

import com.wuseguang.springcloud.service.TheThirdPartyService;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;


public class Server8004Handler extends IoHandlerAdapter  {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TheThirdPartyService theThirdPartyServiceImpl;

    private static Server8004Handler serverHandler ;

    //2通过@PostConstruct实现初始化bean之前进行的操作
    @PostConstruct
    public void init() {
        serverHandler = this;
        //serverHandler.tbBoxService = this.tbBoxService;.
        //3.调用时需要加前缀 如 serverHandler.tbBoxService
    }


    @Override
    public void sessionCreated(IoSession session) throws Exception { //用户连接到服务器
        SocketSessionConfig cfg = (SocketSessionConfig) session.getConfig();
        cfg.setSoLinger(0);
        logger.info("[服务建立]" + session.getId());
    }

    @Override
    public void messageReceived(IoSession session, Object message)throws Exception {//接收消息
        //接收消息
       /* IoBuffer bbuf = (IoBuffer) message;
        byte[] byten = new byte[bbuf.limit()];
        bbuf.get(byten, bbuf.position(), bbuf.limit());
        String temp = HexUtil.binaryToHexString(byten);
        temp = HexUtil.hexStringToString(temp);*/
        logger.info("[收到消息]" + message);
        //操作结果
        String result = theThirdPartyServiceImpl.guangxiZhuzongDocking(message.toString());
        session.write(result);
    }



    @Override
    public void sessionClosed(IoSession session) throws Exception {   //用户从服务器断开
        logger.info("[服务断开]" + session.getId());
        session.close(true);

    }
    @Override
    public void messageSent(IoSession session, Object message){ //发送消息结束
        //logger.info("[发送消息结束]" + session.getId() + "message" + message);
    }


    @Override
    public void sessionIdle(IoSession session, IdleStatus status)throws Exception {//重连
        logger.info("[服务重连]" + session.getId() + "status" + status.toString());
    }


    @Override
    public void exceptionCaught(IoSession session, Throwable cause)throws Exception {//连接发生异常

        logger.info("[服务异常]" + session.getId());
        logger.info("exceptionCaught");
        logger.info("异常信息"+cause);
        if(session!=null){
            session.close(true);
            logger.info("关闭连接");
        }
    }

}
